package com.sugon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.ModuleSpDemandItemDao;
import com.sugon.dao.ModuleSpDemandPlanDao;
import com.sugon.entity.ModuleSpDemandItemEntity;
import com.sugon.entity.ModuleSpDemandPlanEntity;
import com.sugon.service.ModuleSpDemandItemService;
import com.sugon.service.ModuleSpDemandPlanService;
import com.sugon.service.ModuleSpDeptStockService;
import com.sugon.utils.ShiroUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 模具型芯需求计划Service实现类
 *
 * @author sugon
 * @date 2022-07-11 17:08:50
 */
@Service("moduleSpDemandPlanService")
public class ModuleSpDemandPlanServiceImpl implements ModuleSpDemandPlanService {
    @Resource
    private ModuleSpDemandPlanDao moduleSpDemandPlanDao;
    @Resource
    private ModuleSpDemandItemDao moldSpDemandItemDao;
    @Resource
    private ModuleSpDemandItemService moldSpDemandItemService;
    @Resource
    private ModuleSpDeptStockService moldSpDeptStockService;

    @Override
    public Map<Integer, List<Map<String, Object>>> prepareExportTemplateData(Map<String, Object> params) {
        Map<Integer, List<Map<String, Object>>> result = MapUtil.newHashMap();
        List<Map<String, Object>> temMap = CollectionUtil.newArrayList();
        List<ModuleSpDemandPlanEntity> moldSpPlanList = moduleSpDemandPlanDao.listQuery(params);
        if (CollectionUtil.isNotEmpty(moldSpPlanList)) {
            for (ModuleSpDemandPlanEntity moldSpPlan : moldSpPlanList) {
                moldSpPlan.setSheetName(moldSpPlan.getPlanName());
                int idx = 1;
                List<ModuleSpDemandItemEntity> items = moldSpPlan.getItems();
                for (ModuleSpDemandItemEntity item : items) {
                    item.setIdx(idx++);
                    item.setItemAmount(NumberUtil.mul(item.getUnitPrice(), item.getDemandNum()));
                }
                temMap.add(BeanUtil.beanToMap(moldSpPlan));
            }
            result.put(0, temMap);
        }
        return result;
    }

    @Override
    public void generateMoldSpPlan() {
        // 获取下一月份
        DateTime nextMonth = DateUtil.offsetMonth(DateUtil.date(), 1);
        String nextMonthStr = DateUtil.format(nextMonth, DatePattern.NORM_MONTH_PATTERN);
        int yearly = nextMonth.getField(DateField.YEAR);
        int monthly = nextMonth.getField(DateField.MONTH) + 1;

        // 1、清空指定月份的所有型芯采购计划
        moduleSpDemandPlanDao.batchDeleteMoldSpPlan(nextMonthStr);

        // 2、获取下月需求明细
        List<ModuleSpDemandItemEntity> demandItemList = queryMonthlyDemandItem(nextMonthStr);

        Map<String, List<ModuleSpDemandItemEntity>> workshopDemandItemMap = demandItemList.stream().collect(Collectors.groupingBy(ModuleSpDemandItemEntity::getWorkshop));
        // 先按照车间分组
        workshopDemandItemMap.forEach((workshop, deptDemandItems) -> {
            // 在按照供应商分组
            Map<String, List<ModuleSpDemandItemEntity>> supplierDemandItemMap = deptDemandItems.stream().collect(Collectors.groupingBy(ModuleSpDemandItemEntity::getSupplier));

            String supplierIndex = "";
            Set<Map.Entry<String, List<ModuleSpDemandItemEntity>>> entries = supplierDemandItemMap.entrySet();

            for (Map.Entry<String, List<ModuleSpDemandItemEntity>> entry : entries) {
                String supplier = entry.getKey();
                List<ModuleSpDemandItemEntity> supplierDemandItems = entry.getValue();
                // 保存型芯采购计划
                ModuleSpDemandPlanEntity demandPlan = new ModuleSpDemandPlanEntity();
                demandPlan.setWorkshop(workshop);
                demandPlan.setSupplier(supplier);
                demandPlan.setDemandMonth(nextMonthStr);
                supplierIndex = com.sugon.modules.utils.StrUtil.increase(supplierIndex, "", 3, 1);
                demandPlan.setPlanName(StrUtil.format("{}{}-{}-{}型芯制作明细", yearly, supplierDemandItems.get(0).getWorkshopName(), monthly, supplierIndex));
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (ModuleSpDemandItemEntity supplierDemandItem : supplierDemandItems) {
                    totalAmount = totalAmount.add(NumberUtil.mul(supplierDemandItem.getUnitPrice(), supplierDemandItem.getDemandNum()));
                }
                demandPlan.setTotalAmount(totalAmount);
                // 保存成功后更新模具型芯采购计划
                int save = save(demandPlan);
                if (save > 0) {
                    for (ModuleSpDemandItemEntity supplierDemandItem : supplierDemandItems) {
                        supplierDemandItem.setTransitNum(supplierDemandItem.getDemandNum());
                        supplierDemandItem.setPlanId(demandPlan.getId());
                        int updateNum = moldSpDemandItemService.update(supplierDemandItem);
                        if (updateNum > 0) {
                            // 更新车间在途数
                            moldSpDeptStockService.realtimeUpdateDeptStock(supplierDemandItem.getWorkshop(), supplierDemandItem.getMoldSpId());
                        }
                    }
                }
            }
        });
    }

    private List<ModuleSpDemandItemEntity> queryMonthlyDemandItem(String nextMonthStr) {
        Map<String, Object> param = MapUtil.newHashMap();
        param.put("nextMonth", nextMonthStr);
        List<ModuleSpDemandItemEntity> demandItemList = moldSpDemandItemDao.queryList(param);
        return demandItemList;
    }

    @Override
    public ModuleSpDemandPlanEntity queryObject(String id) {
        return moduleSpDemandPlanDao.queryObject(id);
    }

    @Override
    public List<ModuleSpDemandPlanEntity> queryList(Map<String, Object> map) {
        return moduleSpDemandPlanDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return moduleSpDemandPlanDao.queryTotal(map);
    }

    @Override
    public int save(ModuleSpDemandPlanEntity moduleSpDemandPlan) {
        moduleSpDemandPlan.setId(RandomUtil.randomString(32));
        moduleSpDemandPlan.setCreateUser(ShiroUtils.getUserId());
        moduleSpDemandPlan.setGmtCreate(DateUtil.date());
        return moduleSpDemandPlanDao.save(moduleSpDemandPlan);
    }

    @Override
    public int update(ModuleSpDemandPlanEntity moduleSpDemandPlan) {
        return moduleSpDemandPlanDao.update(moduleSpDemandPlan);
    }

    @Override
    public int delete(String id) {
        return moduleSpDemandPlanDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return moduleSpDemandPlanDao.deleteBatch(ids);
    }
}
